import WxRequest from "./request";
import { getStorage, clearStorage, setStorage } from "./storage";
import { modal, toast } from "./extendApi";
import { env } from "./env";

// 对 WxRequest 进行实例化
const instance = new WxRequest({
  baseURL: env.baseURL,
  timeout: 60000,
  isLoading: true,
});

// 防重复刷新token的标识
let isRefreshing = false;
let failedQueue = [];

// 刷新token的方法
const refreshToken = async () => {
  const userInfo = getStorage("userInfo");
  if (!userInfo || !userInfo.id || !userInfo.openid) {
    throw new Error("用户信息不完整");
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: env.baseURL + "/user/updateusertoken",
      method: "POST",
      data: { id: userInfo.id, openid: userInfo.openid },
      header: {
        "Content-Type": "application/json",
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          let newToken;
          if (typeof res.data === "string") {
            try {
              const parsed = JSON.parse(res.data);
              newToken = parsed.data;
            } catch (e) {
              newToken = res.data;
            }
          } else {
            newToken = res.data.data || res.data;
          }
          resolve(newToken);
        } else {
          reject(res);
        }
      },
      fail: reject,
    });
  });
};

// 需要使用测试域名的接口配置（已恢复为正式域名）
const testDomainApis = {
  '/project/projectById/': 'https://kuaizu.xyz',
  '/project/queryProjectByIntroduce': 'https://kuaizu.xyz',
  '/fileUploadController/querImgList': 'https://kuaizu.xyz',
};

// 检查并替换域名
const replaceBaseURL = (config) => {
  const url = config.pluginUrl || '';
  for (const [path, domain] of Object.entries(testDomainApis)) {
    if (url.includes(path) || url === path) {
      config.url = domain + url;
      return config;
    }
  }
  return config;
};

// 配置请求拦截器
instance.interceptors.request = (config) => {
  if (config.pluginUrl && config.pluginUrl.includes("/user/updateusertoken")) {
    return config;
  }

  // 替换特殊接口的域名
  config = replaceBaseURL(config);

  const token = getStorage("token");
  if (token) {
    config.header["Authorization"] = token;
  }

  return config;
};

// 配置响应拦截器
instance.interceptors.response = async (response) => {
  const { isSuccess, data } = response;

  if (!isSuccess) {
    wx.toast({
      title: "网络异常请重试",
      icon: "error",
    });
    console.error(
      `<--后端响应错误:\n\t向后端接口 ${response.config.baseURL == "https://kuaizu.xyz" ? response.config.pluginUrl : response.config.url} 发送 ${response.config.method} 请求时发生错误`,
      `\n\t后端响应状态码： ${response.statusCode}`,
      `\n\t响应信息： ${data.message ? data.message : "无法读取响应信息"}`,
      "\n\n\t收到的完整的后端响应内容：",
      response,
    );
    return response;
  }

  // 处理401错误
  if (
    response.statusCode === 401 &&
    !response.config.pluginUrl?.includes("/user/updateusertoken")
  ) {
    console.log("检测到401错误，开始处理token刷新");

    const userInfo = getStorage("userInfo");
    if (!userInfo || !userInfo.id || !userInfo.openid) {
      console.log("用户信息不完整，跳转登录页");
      clearStorage();
      return Promise.reject(response);
    }

    if (isRefreshing) {
      return new Promise((resolve) => {
        failedQueue.push({ resolve, config: response.config });
      });
    }

    isRefreshing = true;

    try {
      const newToken = await refreshToken();
      console.log("token刷新成功，新token:", newToken);

      setStorage("token", newToken);

      failedQueue.forEach(({ resolve, config }) => {
        resolve(instance.request(config));
      });
      failedQueue = [];

      return instance.request(response.config);
    } catch (error) {
      console.error("刷新token失败:", error);
      clearStorage();
      wx.reLaunch({
        url: "/pages/login/login",
      });
      return Promise.reject(response);
    } finally {
      isRefreshing = false;
    }
  }

  if (response.statusCode === 200)
    console.log(
      `<--后端响应:\n\t向后端接口 ${response.config.baseURL == "https://kuaizu.xyz" ? response.config.pluginUrl : response.config.url} 发送 ${response.config.method} 请求`,
      `\n\t后端响应状态码： ${response.statusCode}`,
      `\n\t响应信息： ${data.message ? data.message : "无法读取响应信息"}`,
      "\n\n\t收到的完整的后端响应内容：",
      response,
    );
  else
    console.warn(
      `<--后端响应:\n\t向后端接口 ${response.config.baseURL == "https://kuaizu.xyz" ? response.config.pluginUrl : response.config.url} 发送 ${response.config.method} 请求`,
      `\n\t后端响应状态码： ${response.statusCode}`,
      `\n\t响应信息： ${data.message ? data.message : "无法读取响应信息"}`,
      "\n\n\t收到的完整的后端响应内容：",
      response,
    );

  switch (data.code) {
    case 200:
      return data;

    case 208:
      const res = await modal({
        content: "鉴权失败，请重新登录",
        showCancel: false,
      });

      if (res) {
        clearStorage();
        wx.navigateTo({
          url: "/pages/login/login",
        });
      }
      return Promise.reject(response);

    default:
      return Promise.reject(response);
  }
};

export default instance;